package com.demo.order.controller;

import com.demo.order.entity.SeckillOrder;
import com.demo.order.service.SeckillOrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * 秒杀订单控制器
 * 提供订单相关的API接口
 */
@Slf4j
@RestController
@RequestMapping("/api/order")
public class SeckillOrderController {

    @Autowired
    private SeckillOrderService seckillOrderService;

    /**
     * 支付订单
     * @param orderId 订单ID
     * @return 支付结果
     */
    @PostMapping("/pay/{orderId}")
    public Map<String, Object> payOrder(@PathVariable Long orderId) {
        log.info("接收到支付订单请求，orderId: {}", orderId);
        
        try {
            return seckillOrderService.payOrder(orderId);
        } catch (Exception e) {
            log.error("支付订单异常，orderId: {}", orderId, e);
            return Map.of(
                    "success", false,
                    "message", "系统异常，请稍后重试"
            );
        }
    }

    /**
     * 查询用户订单
     * @param userId 用户ID
     * @param productId 商品ID（可选）
     * @return 订单列表
     */
    @GetMapping("/user/{userId}")
    public Map<String, Object> getUserOrders(@PathVariable Long userId,
                                            @RequestParam(required = false) Long productId) {
        log.info("查询用户订单，userId: {}, productId: {}", userId, productId);
        
        try {
            List<SeckillOrder> orders;
            if (productId != null) {
                orders = seckillOrderService.getOrdersByUserAndProduct(userId, productId);
            } else {
                // 如果没有指定商品ID，这里可以扩展查询所有订单的方法
                orders = List.of(); // 暂时返回空列表
            }
            
            return Map.of(
                    "success", true,
                    "message", "查询成功",
                    "data", orders
            );
        } catch (Exception e) {
            log.error("查询用户订单异常，userId: {}", userId, e);
            return Map.of(
                    "success", false,
                    "message", "查询失败"
            );
        }
    }

    /**
     * 查询订单详情
     * @param orderId 订单ID
     * @return 订单详情
     */
    @GetMapping("/detail/{orderId}")
    public Map<String, Object> getOrderDetail(@PathVariable Long orderId) {
        log.info("查询订单详情，orderId: {}", orderId);
        
        try {
            SeckillOrder order = seckillOrderService.getOrderById(orderId);
            if (order != null) {
                return Map.of(
                        "success", true,
                        "message", "查询成功",
                        "data", order
                );
            } else {
                return Map.of(
                        "success", false,
                        "message", "订单不存在"
                );
            }
        } catch (Exception e) {
            log.error("查询订单详情异常，orderId: {}", orderId, e);
            return Map.of(
                    "success", false,
                    "message", "查询失败"
            );
        }
    }

    /**
     * 取消超时订单（管理员接口）
     * @return 取消结果
     */
    @PostMapping("/cancel-expired")
    public Map<String, Object> cancelExpiredOrders() {
        log.info("接收到取消超时订单请求");
        
        try {
            return seckillOrderService.cancelExpiredOrders();
        } catch (Exception e) {
            log.error("取消超时订单异常", e);
            return Map.of(
                    "success", false,
                    "message", "操作失败"
            );
        }
    }

    /**
     * 健康检查
     * @return 健康状态
     */
    @GetMapping("/health")
    public Map<String, Object> health() {
        return Map.of(
                "success", true,
                "message", "Order service is running",
                "timestamp", System.currentTimeMillis()
        );
    }

    /**
     * 创建秒杀订单接口（用于测试）
     * @param userId 用户ID
     * @param productId 商品ID
     * @param quantity 购买数量
     * @return 创建结果
     */
    @PostMapping("/seckill/create")
    public Map<String, Object> createOrder(@RequestParam Long userId,
                                          @RequestParam Long productId,
                                          @RequestParam Integer quantity) {
        log.info("接收到创建订单请求，userId: {}, productId: {}, quantity: {}", userId, productId, quantity);
        
        try {
            return seckillOrderService.createSeckillOrder(userId, productId, quantity, null);
        } catch (Exception e) {
            log.error("创建订单异常", e);
            return Map.of(
                    "success", false,
                    "message", "创建订单失败"
            );
        }
    }
}